(function () {
	
    //table数据显示
    var serverData = {};
    var	serverTable;
    var serverData2 = {};
    serverData2.hierarchyId = 0;
    var	serverTable2;
    jQuery(document).ready(function () {
        serverTable=  jQuery('#dataTable').DataTable({
            "serverSide": true,
            "ordering": false,
            "ajax": {
                "dataType": "json",
                "type": "post",
                "cache": false,
                "url": window.rootPath+'/ui/maintainHierarchy/getpage',
                "data": function (d) {
                    return $.extend({}, d, serverData);
                }
            },
            columns: [
	        		{
		            data: null,
		            defaultContent: ""
	        		},
	        		{
                    data: 'id',
                    render: function (data, type, full, meta) {
                        var operate ='<input type="checkbox" dataId="'+data+'" group="addDate"/>';
                        return operate;
                    }
	        		},
	            {
	        			data: 'partName'
	            },
	            {
	            		data: 'manufacturer'
	            },
	            {
		            	data: 'productionTime',
		            	render: function (data, type, full, meta) {
	                    if (data)
	                        return moment(data).format('YYYY/MM/DD');
	                    else
	                        return '';
	                }
	            },
	            {
		            	data: 'installationTime',
		            	render: function (data, type, full, meta) {
		                    if (data)
		                        return moment(data).format('YYYY/MM/DD');
		                    else
		                        return '';
		                }
	            },
	            {
	            		data: 'hierarchy.groupName',
	            },
	            {
        				data: 'manageHierarchy.groupName'
        			},
        			{
        				data: 'maintainHierarchy.groupName'
        			},
	            {
	        			data: 'part',
	        			render: function (data, type, full, meta) {
	        				if (data){
	        					return data.partName + '</br><' + data.partType.title +'>';
	        				}else{
	        					return '';
	        				}
	        			}
	            },
	            {
	            		data: 'state.title'
	            },
                {
                    data:null,
                    defaultContent: "",
                    render: function(data, type, full, meta){
                        var operate = '<button type="button" class="btn btn-sm btn-info addNode" title="绑定"><i class="fa fa-sign-in"></i></button>';
                        return operate;
                    }
                }],
            "drawCallback": function ( oSettings ) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for ( var i=oSettings._iDisplayStart, iLen=total ; i<iLen ; i++ )
                {
                    $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[k] ].nTr ).text( i+1 );
                    k++;
                }

                serverTable.off('click','tr');
                serverTable.on( 'click', 'tr', function (event) {
                    event=event||window.event;
                    var target=event.target||event.scrElement;
                    var data = serverTable.row( this ).data();

                    if(target.className.indexOf('fa-sign-in')!=-1||target.className.indexOf('addNode')!=-1){
                        bindingPart(data,data.partName);
                    }
                    return;
                } );
            }
        });
        
        serverTable2 = jQuery('#dataTable2').DataTable({
	        	"serverSide": true,
	        	"ordering": false,
	        	"ajax": {
	        		"dataType": "json",
	        		"type": "post",
	        		"cache": false,
	        		"url": window.rootPath+'/ui/maintainHierarchy/getpagebyhierarchy',
	        		"data": function (d) {
	        			return $.extend({}, d, serverData2);
	        		}
	        	},
	        	columns: [
	        		{
	        			data: null,
	        			defaultContent: ""
	        		},
	        		{
                    data: 'id',
                    render: function (data, type, full, meta) {
                        var operate ='<input type="checkbox" dataId="'+data+'" group="removeDate"/>';
                        return operate;
                    }
	        		},
	        		{
	        			data: 'partName'
	        		},
	        		{
	        			data: 'manufacturer'
	        		},
	        		{
	        			data: 'productionTime',
	        			render: function (data, type, full, meta) {
	        				if (data)
	        					return moment(data).format('YYYY/MM/DD');
	        				else
	        					return '';
	        			}
	        		},
	        		{
	        			data: 'installationTime',
	        			render: function (data, type, full, meta) {
	        				if (data)
	        					return moment(data).format('YYYY/MM/DD');
	        				else
	        					return '';
	        			}
	        		},
	        		{
	        			data: 'hierarchy.groupName'
	        		},
	        		{
	        			data: 'part',
	        			render: function (data, type, full, meta) {
	        				if (data){
	        					return data.partName + '-' + data.partType.title;
	        				}else{
	        					return '';
	        				}
	        			}
	        		},
	        		{
	        			data: 'manageHierarchy.groupName'
	        		},
	        		{
	        			data: 'maintainHierarchy.groupName'
	        		},
	        		{
	        			data: 'state.title'
	        		},
	        		{
	        			data:null,
	        			defaultContent: "",
	        			render: function(data, type, full, meta){
	        				var operate = '<button type="button" class="btn btn-sm btn-info addNode" title="移除"><i class="fa fa-remove"></i></button>';
	        				return operate;
        			}
        		}],
        		"drawCallback": function ( oSettings ) {
        			var k = 0;
        			var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;
        			
        			for ( var i=oSettings._iDisplayStart, iLen=total ; i<iLen ; i++ )
        			{
        				$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[k] ].nTr ).text( i+1 );
        				k++;
        			}
        			
        			serverTable2.off('click','tr');
        			serverTable2.on( 'click', 'tr', function (event) {
        				event=event||window.event;
        				var target=event.target||event.scrElement;
        				var data = serverTable2.row( this ).data();
        				
        				if(target.className.indexOf('fa-remove')!=-1||target.className.indexOf('addNode')!=-1){
        					unbind(data,data.partName);
        				}
        				return;
        			} );
        		}
        });
        
        //查询
        jQuery('.searchBtn').on('click',function(){
            serverData.key=jQuery('#search').val();
            serverTable.draw();
        })
        
        //撤销查询
        jQuery('.resetBtn').on("click",function()
        {
            jQuery('#search').val('');
            serverData.key ='';
            serverTable.draw();
        });
        
        //查询2
        jQuery('.searchBtn2').on('click',function(){
        		var id = serverData2.hierarchyId;
        		if(id == '' || id == '0'){
        			message("请选择部门层级!");
        			return;
        		}
        		serverData2.key=jQuery('#search').val();
        		serverTable2.draw();
        })
        
        //撤销查询2
        jQuery('.resetBtn2').on("click",function(){
	        	jQuery('#search2').val('');
	        	serverData2.key ='';
	        	serverTable2.draw();
    		});
        
        
    });

    
    //未绑定 全选
    $("#allNotBound").click(function() {
    		var addDate = $(":checkbox[group=addDate]");
        if ($(this).prop("checked")) {
        		addDate.each(function() {
                $(this).prop("checked", true);  
            });  
        } else {  
        		addDate.each(function() {  
                $(this).prop("checked", false);  
            });  
        }  
    }); 
    
    //已绑定 全选
    $("#allBound").click(function() {
	    	var removeDate = $(":checkbox[group=removeDate]");
	    	if ($(this).prop("checked")) {
	    		removeDate.each(function() {
	    			$(this).prop("checked", true);  
	    		});  
	    	} else {  
	    		removeDate.each(function() {  
	    			$(this).prop("checked", false);  
	    		});  
	    	}  
    }); 
    
    //获取全选数据
    function getSelectData(group){
    		var obj = $(":checkbox[group="+group+"]:checked");
    		var myArray = new Array();
    		var i =0;
    		obj.each(function() {
    			myArray[i++] = $(this).attr('dataId');
    		});
    		return myArray;
    }
    
    //绑定全部信息
    jQuery('.addBtn').on('click', function() {
		var id = serverData2.hierarchyId;
		if(id == '' || id == '0'){
			message("请选择权属部门!");
			return;
		}
	    	var dataInfo = getSelectData('addDate');
	    	if(dataInfo.length == 0){
	    		message('请选择需要绑定的部件信息!');
			return;
	    	}
	    	var d = {
	    			"Id" : id,
	    			"dataInfo" : dataInfo
	    		};
	    	var url = window.rootPath +'/ui/maintainHierarchy/addDataAll';
	    	$("#right").mLoading("show");
        jQuery.ajax({
            url:encodeURI(url),
            cache:false,
            type :"post",
            data: JSON.stringify(d),
            dataType:"json",
            contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
            success:function(data){
            		$("#allNotBound").prop("checked", false); 
            		$("#allBound").prop("checked", false); 
				message(data.msg);
				serverTable.draw(false);
				serverTable2.draw(false);
				$("#right").mLoading("hide");
            }
        });
    });
    
    //移除全部信息
    jQuery('.deleteBtn').on('click', function() {
    		var dataInfo = getSelectData('removeDate');
		if(dataInfo.length == 0){
			message('请选择需要移除的部件信息!');
			return;
		}
	    	var d = {
	    			"dataInfo" : dataInfo
	    		};
	    	var url = window.rootPath +'/ui/maintainHierarchy/removeDataAll';
	    	$("#right").mLoading("show");
	    	jQuery.ajax({
	    		url:encodeURI(url),
	    		cache:false,
	    		type :"post",
	    		data: JSON.stringify(d),
	    		dataType:"json",
	    		contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
	    		success:function(data){
	    			$("#allNotBound").prop("checked", false); 
            		$("#allBound").prop("checked", false); 
	    			message(data.msg);
	    			serverTable.draw(false);
				serverTable2.draw(false);
				$("#right").mLoading("hide");
	    		}
	    	});
    });
    
    ////////////////初始化模型的树结构/////////////////////////
    var modalSetting = {
        edit:{
            enable: false,
            showRemoveBtn:false,
            showRenameBtn:false,
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "parentId",
                rootParentId: 0
            }
        },
        view:{
            showLine:true
        },
        check: {
			enable: false,
			chkStyle: "radio",
			radioType: "level"
		},
        callback:{
            onClick:getPartBaseInfo
        }

    };
    
    function getPartBaseInfo(e, treeId, treeNode){
    		var Id=treeNode.id;
		//if('0' == Id) return;
		serverData2.hierarchyId =Id;
		serverTable2.draw();
		
    }
    
    
    //初始化 层级树
    var primaryNode=[];
    var url = window.rootPath +'/ui/maintainHierarchy/getAllNodes';
    jQuery.ajax({
        url:url,
        cache:false,
        type :"get",
        data:'',
        dataType:"json",
        contentType:'application/json;charset=utf-8',//解决返回数据中的中文乱码问题
        success:function(data){
            primaryNode.push(
                {
                    id: 0,
                    name: "部门层级",
                    open: "true"
                    // iconSkin:"diy03"
                }
            );
            for (var i = 0; i < data.nodes.length; i++) {
                primaryNode.push(data.nodes[i]);
            }
            $.fn.zTree.init($("#hierarchyTree"),modalSetting,primaryNode);
        }
    });
    
    //绑定数据
    function bindingPart(data,levelName){
        var treeObj= $.fn.zTree.getZTreeObj("hierarchyTree");
        var selectNodes=treeObj.getSelectedNodes(treeObj);
        var selectNode=selectNodes[0];
        if(selectNode){
        		if(selectNode.id == '0'){
        			message('不能绑定到此层级!');
        			return;
        		}
            $.springLemonDialog({
                title:'系统提示',//标题   默认为   系统提示
                content:'是否要绑定'+levelName+'？',//确认文本
                bootstrapModalOption:{keyboard: true},
                clickButton:function(sender,modal,index){//按钮事件处理
                    //index:0 确认    1：取消
                    //sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
                    if(index==0){
                        var url=window.rootPath+'/ui/maintainHierarchy/binding';
                        var d = {
                                "hierarchyId":selectNode.id,
                                "id":data.id
                            };
                        $("#right").mLoading("show");
                        jQuery.ajax({
                            url:encodeURI(url),
                            cache:false,
                            type :"post",
                            data: JSON.stringify(d),
                            dataType:"json",
                            contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
                            success:function(data){
                            		message(data.msg);
                                serverTable.draw(false);
                                serverTable2.draw(false);
                                $("#right").mLoading("hide");
                            }
                        });
                    }
                    $(this).closeDialog(modal);
                }
            });
        }else{
            $.springLemonDialog({
                title:'系统提示',//标题   默认为   系统提示
                content:'请选择一个节点',//确认文本
                bootstrapModalOption:{keyboard: true},
                clickButton:function(sender,modal,index){//按钮事件处理
                    //index:0 确认    1：取消
                    //sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
                    $(this).closeDialog(modal);
                }

            });
        }
    }
    
    //解绑数据
    function unbind(data,levelName){
    		var treeObj= $.fn.zTree.getZTreeObj("hierarchyTree");
    		var selectNodes=treeObj.getSelectedNodes(treeObj);
    		var selectNode=selectNodes[0];
    		$.springLemonDialog({
    			title:'系统提示',//标题   默认为   系统提示
    			content:'是否解除绑定'+levelName+'？',//确认文本
    			bootstrapModalOption:{keyboard: true},
    			clickButton:function(sender,modal,index){//按钮事件处理
    				//index:0 确认    1：取消
    				//sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
    				if(index==0){
    					var url=window.rootPath+'/ui/maintainHierarchy/unbind/'+data.id;
    					$("#right").mLoading("show");
    					jQuery.ajax({
    						url:encodeURI(url),
    						cache:false,
    						type :"post",
    						data: '',
    						dataType:"json",
    						contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
    						success:function(data){
    							message(data.msg);
    							serverTable.draw(false);
    							serverTable2.draw(false);
    							$("#right").mLoading("hide");
    						}
    					});
    				}
    				$(this).closeDialog(modal);
    			}
    		});
    }
    
})();